package com.zf.shuashua.ui.home;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.mediamain.android.view.FoxWallView;
import com.mediamain.android.view.bean.MessageData;
import com.mediamain.android.view.interfaces.FoxListener;
import com.meis.base.mei.adapter.BaseMultiAdapter;
import com.meis.base.mei.base.BaseMultiListFragment;
import com.meis.base.mei.constant.DataConstants;
import com.meis.base.mei.entity.Result;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.qq.e.ads.nativ.NativeExpressADView;
import com.qq.e.comm.util.AdError;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.hot.HotByteAdListener;
import com.zf.shuashua.advert.hot.HotTencentAdListener;
import com.zf.shuashua.advert.hot.NativeByteHotManager;
import com.zf.shuashua.advert.hot.NativeTencentHotManager;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.BannerBean;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.FocusType;
import com.zf.shuashua.bean.advert.AdvertConfigBean;
import com.zf.shuashua.bean.home.HotVideoEntity;
import com.zf.shuashua.event.HotVideoEvent;
import com.zf.shuashua.event.RecordPlayEvent;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.adapter.HotVideoMultiAdapter;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.mine.FriendsDetailsActivity;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.utils.SwitchUtil;
import com.zf.shuashua.utils.Util;
import com.zf.shuashua.widget.SampleCoverVideo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import io.reactivex.Observable;

public class HotVideoFragment extends BaseMultiListFragment<HotVideoEntity> {

    private int currentJumpPos = -1;
    private RecyclerView recyclerView;
    private HotVideoMultiAdapter hotAdapter;
    private LinearLayoutManager linearLayoutManager;
    //    private List<NativeExpressADView> nativeExpressADViews;

    private List<View> nativeExpressADViews = new ArrayList<>();
    private String uuiThirdAdvert;
    private static final int MAY_REQUEST_AD_NUM = 3;
    // 第一页是否加载过广告
//    private boolean isLoadedAdFirstPage = false;
    private FoxWallView mOxWallView;
    private ImageView icDwj;
    private boolean isShowTuia = false;

    private ValueAnimator weltAnimator1;
    private boolean isClickGoldEnable1 = true;
    private float dragX1;
    private float dragY1;
    private RelativeLayout flContainer;

    public static HotVideoFragment newInstance() {
        Bundle args = new Bundle();
        HotVideoFragment fragment = new HotVideoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        super.initView();
        mOxWallView = (FoxWallView) findViewById(R.id.TMAw1);
        icDwj = findViewById(R.id.icDwj);
        flContainer = getView().findViewById(R.id.rl_container);
        initFoxView();
        setUpDwj();
        getFoxSource();
    }

    /**
     * 首页悬浮按钮（自身活动或者推啊广告）
     */
    private void getFoxSource(){
        HttpData.getInstance().getUserBannerList("2", new ACallback<String>() {
            @Override
            public void onSuccess(String data) {
                try{
                    List<BannerBean> bannerList = ParseJsonUtils.parseListData(data, "data", BannerBean.class);
                    if(bannerList != null && bannerList.size() > 0){
                        BannerBean banner = bannerList.get(0);
                        if(banner.isTuia()){
                            isShowTuia = true;
                            showTuia();
                        }else{
                            isShowTuia = false;
                            mOxWallView.setVisibility(View.GONE);
                            icDwj.setVisibility(View.VISIBLE);
                            Glide.with(mActivity).load(banner.banner_url)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .into(icDwj);

                            icDwj.setOnClickListener(view -> {
                                if (icDwj.getVisibility() == View.VISIBLE && isClickGoldEnable1) {
                                    if (!Store.getInstance().isLogin()) {
                                        mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
                                    } else {
                                        startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + banner.jump_link).putExtra("title", banner.banner_name));
                                    }
                                }
                            });
                        }
                    }
                }catch (Exception ignored){

                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }

    /**
     * 推啊悬浮按钮
     */
    private void initFoxView() {
        mOxWallView.setAdListener(new FoxListener() {
            @Override
            public void onReceiveAd() {
                Log.d("========", "onReceiveAd");
            }

            @Override
            public void onFailedToReceiveAd(int errorCode, String errorMsg) {
                Log.d("========", "onFailedToReceiveAd  Message=" + errorMsg);
            }

            @Override
            public void onLoadFailed() {
                Log.d("========", "onLoadFailed");
            }

            @Override
            public void onCloseClick() {
                Log.d("========", "onCloseClick");
            }

            @Override
            public void onAdClick() {
                Log.d("========", "onAdClick");
            }

            @Override
            public void onAdExposure() {
                Log.d("========", "onAdExposure");
            }

            @Override
            public void onAdActivityClose(String s) {
                Log.d("========", "onAdActivityClose" + s);
//                if (!FoxBaseCommonUtils.isEmpty(s)){
//                    ToastUtils.showShort(s);
//                }
            }

            @Override
            public void onAdMessage(MessageData messageData) {

            }
        });
//        if(mOxWallView != null){
//            String userId = Store.getInstance().getuserId();
//            if(TextUtils.isEmpty(userId)){
//                userId = Util.getDeviceId(ShuaApplication.getContext());
//            }
//            mOxWallView.loadAd(361361,userId);
//        }
    }

    /**
     * 设置活动按钮可移动
     */
    @SuppressLint("ClickableViewAccessibility")
    private void setUpDwj(){
        icDwj.setOnTouchListener((v, event) -> {
            if (weltAnimator1 != null && weltAnimator1.isRunning()) {
                return false;
            }
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isClickGoldEnable1 = true;
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    dragX1 = event.getRawX();
                    dragY1 = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - dragX1;
                    float dy = event.getRawY() - dragY1;

                    if (isClickGoldEnable1) {
                        if (Math.abs(dx) >= 5 || Math.abs(dy) >= 5) {
                            isClickGoldEnable1 = false;
                        }
                    }

                    float x = v.getX() + dx;
                    float y = v.getY() + dy;

                    if (x <= 0) {
                        x = 0;
                    }

                    if (y <= 0) {
                        y = 0;
                    }

                    if (x >= flContainer.getWidth() - v.getWidth()) {
                        x = flContainer.getWidth() - v.getWidth();
                    }

                    if (y >= flContainer.getHeight() - v.getHeight()) {
                        y = flContainer.getHeight() - v.getHeight();
                    }

                    v.setX(x);
                    v.setY(y);

                    dragX1 = event.getRawX();
                    dragY1 = event.getRawY();

                    break;
                case MotionEvent.ACTION_UP:
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    int width = flContainer.getWidth();
                    int height = flContainer.getHeight();
                    if (v.getX() == 0 || v.getX() == width - v.getWidth()) {
                        break;
                    }

                    int end = 0;

                    float centerX = v.getX() + v.getWidth() / 2;

                    if (centerX >= width / 2) {
                        end = width - v.getWidth();
                    } else {
                        end = 0;
                    }

                    weltAnimator1 = ValueAnimator.ofInt((int) v.getX(), end);
                    weltAnimator1.setDuration(400);
                    weltAnimator1.addUpdateListener(animation -> {
                        int value = (int) animation.getAnimatedValue();
                        v.setX(value);
                    });
                    weltAnimator1.start();

                    break;
            }
            return false;
        });
    }

    private void showTuia() {
        if (!isShowTuia) {
            return;
        }
        mOxWallView.setVisibility(View.VISIBLE);
        icDwj.setVisibility(View.GONE);
        if (mOxWallView != null) {
            mOxWallView.post(() -> {
                String userId = Store.getInstance().getuserId();
                if (TextUtils.isEmpty(userId)) {
                    userId = Util.getDeviceId(ShuaApplication.getContext());
                }
                mOxWallView.loadAd(361361, userId);
            });
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
//        showTuia();
    }

    @Override
    protected RecyclerView getRecyclerView() {
        recyclerView = findViewById(R.id.recycler);
        recyclerView.setLayoutManager(linearLayoutManager = new LinearLayoutManager(getContext()));
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //大于0说明有播放
                if (GSYVideoManager.instance().getPlayPosition() >= 0) {
                    //当前播放的位置
                    int position = GSYVideoManager.instance().getPlayPosition();
                    //对应的播放列表TAG
                    if (GSYVideoManager.instance().getPlayTag().equals(HotVideoMultiAdapter.TAG)
                            && (position < firstVisibleItem || position > lastVisibleItem)) {

                        //如果滑出去了上面和下面就是否，和今日头条一样
                        //是否全屏
                        if (!GSYVideoManager.isFullState(mActivity)) {
                            GSYVideoManager.releaseAllVideos();
                            hotAdapter.notifyItemChanged(position);
                        }
                    }
                }
            }
        });
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        return recyclerView;
    }

    private int getRate() {
        return ShuaApplication.horizontalRate;
    }

    @Override
    protected void loadPage(int pageNo) {
        setPageSize(pageNo == DataConstants.FIRST_PAGE ? (getRate() * (MAY_REQUEST_AD_NUM - 1) + 1) : getRate() * MAY_REQUEST_AD_NUM);
        super.loadPage(pageNo);
    }

    @Override
    protected BaseMultiAdapter<HotVideoEntity> getAdapter() {
        return hotAdapter = new HotVideoMultiAdapter(mActivity, new HotVideoMultiAdapter.OnItemClickListener() {
            @Override
            public void onJumpDetail(SampleCoverVideo videoView, GSYVideoViewBridge viewBridge, HotVideoEntity entity, int position) {
                currentJumpPos = position;
                SwitchUtil.savePlayState(videoView);
                viewBridge.setLastListener(videoView);
                HotVideoDetailActivity.startTActivity((Activity) getContext(), entity, videoView);
            }

            @Override
            public void onFollow(int userId, int position) {
                HttpData.getInstance().getFocusType(userId, new AbsCallback<BaseData<FocusType>>() {
                    @Override
                    public void onRealSuccess(BaseData<FocusType> data) {
                        switch (data.getData().getFollow_status()) {
                            //未关注
                            case 0:
                                break;
                            case 1://已关注
                            case 2://相互关注
                                if (hotAdapter.getData().size() > position) {
                                    hotAdapter.getData().get(position).follow_status = 1;
                                    hotAdapter.notifyItemChanged(position);
                                    Toast.makeText(mActivity, "关注成功", Toast.LENGTH_SHORT).show();
                                }
                                break;
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        LogUtil.d(errMsg);
                    }
                });
            }

            @Override
            public void onJumpUserDetail(int userId, int position) {
                if (!Store.getInstance().getuserId().equals(userId + "")) {
                    reportAdvertAction(TrackConstants.ACTION_HOME_MESSAGE, TrackConstants.NOTE_HOME_MESSAGE);
                }
                currentJumpPos = position;
                mActivity.startActivity(new Intent(mActivity, FriendsDetailsActivity.class).putExtra("USER_ID", userId + ""));
            }
        });
    }

    @Override
    public void onRefreshing() {
//        isLoadedAdFirstPage = false;
        lastAdPosition = 0;
        super.onRefreshing();
    }

    @Override
    protected Observable<Result<List<HotVideoEntity>>> getListObservable(int pageNo) {
        return HttpData.getInstance().getHotList(pageNo, getPageSize()).map(s -> {
            Result<List<HotVideoEntity>> result = new Result<>();
            result.data = new ArrayList<>();
            //热点视频列表
            if (!TextUtils.isEmpty(s)) {
                result.data = ParseJsonUtils.parseListData(s, "data", HotVideoEntity.class);
            }

//            // 判定第一页数据是否已经加载过广告
//            if (pageNo == DataConstants.FIRST_PAGE) {
//                if (!isLoadedAdFirstPage && nativeExpressADViews.size() > 0 && result.data != null && result.data.size() > 1) {
//                    isLoadedAdFirstPage = true;
//                    HotVideoEntity adEntity = coverAdToHotBean(nativeExpressADViews.get(0));
//                    result.data.add(1, adEntity);
//                    for (int i = 1; i < nativeExpressADViews.size(); i++) {
//                        if (result.data.size() >= i * getRate() + i + 1) {
//                            result.data.add(i * getRate() + i + 1, coverAdToHotBean(nativeExpressADViews.get(i)));
//                        }
//                    }
//                    // 重置
//                    nativeExpressADViews = new ArrayList<>();
//                }
//            } else {
//                // 处理第二页数据
//                if (nativeExpressADViews.size() > 0 && result.data != null && result.data.size() > 1) {
//                    for (int i = 0; i < nativeExpressADViews.size(); i++) {
//                        if (result.data.size() >= (i + 1) * getRate() + i) {
//                            result.data.add((i + 1) * getRate() + i, coverAdToHotBean(nativeExpressADViews.get(i)));
//                        }
//                    }
//                }
//                // 重置
//                nativeExpressADViews = new ArrayList<>();
//            }

            // 加载广告数据
            requestAdData();

            return result;
        });
    }

    /**
     * 优量汇信息流广告
     */
    private void loadTencentNativeAd(String advertId) {
        if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose() || CommitUtils.isOppoClose()){
            return;
        }
        if (TextUtils.isEmpty(advertId)) {
            advertId = "7071747407734394";
        }
        uuiThirdAdvert = Util.getUUID32();
        NativeTencentHotManager.getInstance().loadFullExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_HOT, advertId, MAY_REQUEST_AD_NUM, new HotTencentAdListener() {
            @Override
            public void onADLoaded(List<NativeExpressADView> adList) {
                if (adList == null || adList.size() < 1) {
                    return;
                }
                nativeExpressADViews = new ArrayList<>();
                nativeExpressADViews.addAll(adList);

                addAdData();
            }

            @Override
            public void onNoAD(AdError adError) {

            }
        });
    }

    /**
     * 穿山甲信息流广告
     */
    private void loadByteNativeAd(String advertId) {
        if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose() || CommitUtils.isOppoClose()){
            return;
        }
        if (TextUtils.isEmpty(advertId)) {
            advertId = "945420044";
        }
        uuiThirdAdvert = Util.getUUID32();
        NativeByteHotManager.getInstance().loadFullExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_HOT, advertId, MAY_REQUEST_AD_NUM, new HotByteAdListener() {
            @Override
            public void onADLoaded(List<TTNativeExpressAd> adList) {
                if (adList == null || adList.size() < 1) {
                    return;
                }
                nativeExpressADViews = new ArrayList<>();
                for (TTNativeExpressAd ttNativeExpressAd : adList) {
                    nativeExpressADViews.add(ttNativeExpressAd.getExpressAdView());
                }

                addAdData();
            }

            @Override
            public void onError(int code, String message) {

            }
        });
    }

    private int lastAdPosition = 0;

    private void addAdData(){
        try{
            if(mAdapter == null || mAdapter.getData().size() < 1 || nativeExpressADViews == null || nativeExpressADViews.size() < 1){
                return;
            }
            for (int i = 0; i < nativeExpressADViews.size(); i++) {
                int tempPosition = lastAdPosition < 1 ? 1: lastAdPosition + getRate() + 1;
                if (tempPosition <=  mAdapter.getData().size()) {
                    lastAdPosition = tempPosition;
                    mAdapter.addData(lastAdPosition, coverAdToHotBean(nativeExpressADViews.get(i)));
                }
            }
            nativeExpressADViews = new ArrayList<>();
        }catch (Exception ignored){

        }
    }

//    private void addFirstPageAdData() {
//        // 第一页未加载过广告
//        if (!isLoadedAdFirstPage && getPageNo() == DataConstants.FIRST_PAGE && mAdapter.getData().size() > 1) {
//            // 第二条插入广告
//            if (nativeExpressADViews.size() > 0) {
//                isLoadedAdFirstPage = true;
//                HotVideoEntity adEntity = coverAdToHotBean(nativeExpressADViews.get(0));
//                mAdapter.addData(1, adEntity);
//
//                for (int i = 1; i < nativeExpressADViews.size(); i++) {
//                    if (mAdapter.getData().size() >= i * getRate() + i + 1) {
//                        mAdapter.getData().add(i * getRate() + i + 1, coverAdToHotBean(nativeExpressADViews.get(i)));
//                    }
//                }
//
//                // 重置
//                nativeExpressADViews = new ArrayList<>();
//            }
//        }
//    }

    private HotVideoEntity coverAdToHotBean(View ad) {
        HotVideoEntity hotVideo = new HotVideoEntity();
        hotVideo.uuiThirdAdvert = uuiThirdAdvert;
        hotVideo.planId = System.identityHashCode(ad) + "";
        hotVideo.view = ad;
        hotVideo.itemType = HotVideoMultiAdapter.AD_STYLE;
        hotVideo.praise_count = new Random().nextInt(10);
        hotVideo.comment_count = new Random().nextInt(5);
        return hotVideo;
    }

    @Override
    protected void initData() {
        super.initData();
    }

    // 请求广告数据
    private void requestAdData() {
        if (ShuaApplication.horizontalConfig == null) {
            requestDefaultAdData();
            return;
        }
        //轮询依次获取横屏信息流的广告配置
        AdvertConfigBean advertConfig = ShuaApplication.horizontalConfig.getHorizontalConfig();
        if (advertConfig == null) {
            requestDefaultAdData();
            return;
        }
        String advertId = advertConfig.getOrigin_id();
        if (advertConfig.isTencent()) {
            loadTencentNativeAd(advertId);
        } else {
            loadByteNativeAd(advertId);
        }
    }

    private void requestDefaultAdData() {
        loadByteNativeAd("");
    }

    @Override
    public boolean canLoadMore() {
        return true;
    }

    @Override
    public boolean canPullToRefresh() {
        return true;
    }

    @Override
    protected boolean loadOnShow() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_list_comm_recycler;
    }

    @Override
    public boolean onBackPressedSupport() {
        if (GSYVideoManager.backFromWindowFull(mActivity)) {
            return true;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.backFromWindowFull(mActivity);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        GSYVideoManager.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (mOxWallView != null) {
            mOxWallView.destroy();
        }
    }

    @Override
    public boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected int getPageSize() {
        return super.getPageSize();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHotVideoEvent(HotVideoEvent event) {
        if (event != null && currentJumpPos != -1 && mAdapter.getData().size() > currentJumpPos) {
            if (event.isControlFollow) {
                mAdapter.getData().get(currentJumpPos).follow_status = event.isFollowed ? 1 : 0;
            } else {
                mAdapter.getData().get(currentJumpPos).is_praise_user = event.isPraised;
                mAdapter.getData().get(currentJumpPos).praise_count = event.praiseCount;
            }
            mAdapter.notifyItemChanged(currentJumpPos);
        }
    }

    // 恢复播放状态
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecordPlayEvent(RecordPlayEvent event) {
        if (event == null || recyclerView == null) return;
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View child = recyclerView.getChildAt(i);
            if (child.getTag() != null && child.getTag().toString().equals(currentJumpPos + "")) {
                SampleCoverVideo videoView = child.findViewById(R.id.video_layout);
                if (videoView != null) {
                    if (event.currentPosition != 0) {
                        videoView.setSeekOnStart(event.currentPosition);
                    }
                    if (event.isPause) {
                        videoView.onVideoPause();
                    } else {
                        videoView.postDelayed(() -> videoView.getStartButton().performClick(), 400);
                    }
                }
            }
        }
    }

    private void reportAdvertAction(String action, String note) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_HOME, action, note);
    }
}
